﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BO.Admin;
using BO;
using System.IO;
using System.Net.Mail;

namespace ProjectQuaDep.Admin.AwardsImages
{
    public partial class Images : System.Web.UI.Page
    {
        DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ShowAll();
            }
        }
        protected void ShowAll()
        {
            string orderby = rbCount.SelectedValue.ToString();
            string CheckShowTheoVong = ddlChontheoquyche.SelectedValue.ToString();
            string search = txtSearch.Text.Trim();
            string startDate = "";//txtStartDate.Text.Trim();
            string endDate = "";//txtEndDate.Text.Trim();
            string dkCount = rbCount.SelectedValue.ToString();
            string status = rbStatus.SelectedValue.ToString();
            string round = ddlRound.SelectedValue.ToString();
            dt = ImagesBO.getAllImagesBO(search, startDate, endDate, dkCount, status, round, CheckShowTheoVong, orderby);
            gvShow.DataSource = dt;
            gvShow.DataBind();
            //SExcel();
        }
        protected void ShowGiaiThuong()
        {
            string getRound = ddlRound.SelectedValue.ToString();
            DataTable dt = new DataTable();
            dt = ImagesBO.GetAllAwardsBO(getRound);
            if (dt.Rows.Count > 0)
            {
                ddlSetGiai.Visible = true;
            }
            else
            {
                ddlSetGiai.Visible = false;
            }
            ddlSetGiai.DataSource = dt;
            ddlSetGiai.DataValueField = Const.tbAwardsWeek.AwardsID;
            ddlSetGiai.DataTextField = Const.tbAwardsWeek.Title;
            ddlSetGiai.DataBind();
            lblPage.Text = "";
        }
        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            String linkclien;
            String linkserver;
            if (fuUploadAnh.HasFile)
            {
                try
                {
                string NameFile = "/Upload/Web/UserImages/" + BO.Const.FormatNameFile + DateTime.Now.ToString("yyyyMMddHHmmss") + fuUploadAnh.FileName;
                linkclien = Server.MapPath(NameFile);
                linkserver = NameFile;
                fuUploadAnh.SaveAs(linkclien);
                BO.Admin.ImagesBO.UpdateImageFileBO(lblID.Text, linkserver);
                ShowAll();
                lblMs.Text = "";
                pnUpdate.Visible = false;
                }
                catch (Exception)
                {
                    lblMs.Text = "Xảy ả lỗi rồi";
                }
            }  
        }

        protected void cmdHide_Click(object sender, EventArgs e)
        {
            pnUpdate.Visible = false;
        }

        protected void cmdSearch_Click(object sender, ImageClickEventArgs e)
        {
            ShowAll();
        }

        protected void cmdAdd_Click(object sender, ImageClickEventArgs e)
        {

        }

        protected void ddlRound_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowAll();
            ShowGiaiThuong();
        }

        protected void gvShow_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvShow.PageIndex = e.NewPageIndex;
            lblPage.Text = "Trang: " + (gvShow.PageIndex + 1).ToString();
            ShowAll();
        }

        protected void gvShow_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string cmdName = e.CommandName.ToString();
            string ID = e.CommandArgument.ToString();

            if (cmdName == "cmdDuyet")
            {
                //duyet
                DataTable dtDuyet = new DataTable();
                dtDuyet = ImagesBO.GetInfomationImagesBO(ID);
                string img = dtDuyet.Rows[0][Const.tbImages.Img].ToString();
                string imgHome = dtDuyet.Rows[0][Const.tbImages.ImgThumb].ToString();
                string imgList = dtDuyet.Rows[0][Const.tbImages.ImgThumbList].ToString();
                string sTitle = dtDuyet.Rows[0][Const.tbImages.Name].ToString();
                string Email = dtDuyet.Rows[0][Const.tbImages.Email].ToString().Trim();
                if (img == "" || imgHome == "" || imgList == "")
                {
                    lblPage.Text = "Chưa cập nhật ảnh list và home không thể duyệt";
                }
                else
                {
                    ImagesBO.EditStatusImagesBO(ID, "1");
                    try
                    {
                        string pGmailEmail = BO.Const.EmailSend;//"dungngtran87";
                        string pGmailPassword = BO.Const.PassEmail;//"longthan";
                        string sLink = BO.Const.sHttpDomain + BO.Utils.BuildLinkDetail(sTitle, ID, "0");
                        string pBody = "Ảnh của bạn đã được duyệt xin cảm ơn bạn!<br/>Bạn có thể xem tại:<a href=\"" + sLink + "\"><b>Đây</b></a>";
                        string pTo =Email ;//"dungnguyentran@channelvn.net";//"nguyenhaitien@vneconomy.vn";
                        string pSubject = BO.Const.pSubject;//"Immukid cuộc thi ảnh";
                        System.Web.Mail.MailFormat pFormat = System.Web.Mail.MailFormat.Html;
                        SendMail(pGmailEmail, pGmailPassword, pTo, pSubject, pBody, pFormat, "");
                    }
                    catch (Exception) { }
                    ShowAll();
                }
            }
            else if (cmdName == "cmdAddVote")
            {
                int kq = ImagesBO.UpdateVoteImagesByPointBO(ID, txtVoteV.Text);
                if (kq == 1)
                {
                    lblPage.Text = "Vote ảo thành công!";
                    ShowAll();
                }
                else
                {
                    lblPage.Text = "Vote ảo thất bại!";
                }
            }
            else if (cmdName == "cmdUploadAnh")
            {
                pnUpdate.Visible = true;
                lblID.Text = ID;
            }
            else if (cmdName == "cmdTieuDiem")
            {
                DataTable dtInfo = new DataTable();
                dtInfo = ImagesBO.GetInfomationImagesBO(ID);
                int IsFocus = int.Parse(dtInfo.Rows[0][Const.tbImages.IsFocus].ToString());
                if (IsFocus == 1)
                {
                    ImagesBO.EditIsFocusImagesBO(ID, "0");
                }
                else
                {
                    ImagesBO.EditIsFocusImagesBO(ID, "1");
                }
                ShowAll();
            }
            else if (cmdName == "cmdKhoa")
            {
                //khoa
                ImagesBO.EditStatusImagesBO(ID, "3");
                ShowAll();
            }
            //
            else if (cmdName == "cmdSelect")
            {
                //set anh doat giai
                DataTable dtInfo = new DataTable();
                dtInfo = ImagesBO.GetInfomationImagesBO(ID);
                int statusImage = int.Parse(dtInfo.Rows[0][Const.tbImages.Status].ToString());
                string round = ddlRound.SelectedValue.ToString();
                if (round == "0")
                {
                    lblPage.Text = "Chọn Vòng Thi";
                }
                else
                {
                    if (statusImage == 0)
                    {
                        lblPage.Text = "Ảnh chưa được duyệt không thể set!";
                        return;
                    }
                    else if (statusImage == 3)
                    {
                        lblPage.Text = "Ảnh bị khóa không thể set!";
                        return;
                    }
                    string GiaiID = ddlSetGiai.SelectedValue.ToString();
                    if (GiaiID == "" || GiaiID == null)
                    {
                        lblPage.Text = "Không có giải nào để chọn!";
                    }
                    else
                    {
                        int kq = ImagesBO.addImgDoatGiaiBO(ID, GiaiID);
                        if (kq == 0)
                        {
                            lblPage.Text = "Set đoạt giải thất bại!";
                        }
                        else
                        {
                            if (kq == -1)
                            {
                                lblPage.Text = "Đã set giải này rồi!";
                            }
                            else
                            {
                                lblPage.Text = "Set đoạt giải thành công!";
                                ShowAll();
                            }
                        }
                    }
                }
            }
        }

        protected void rbStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowAll();
        }

        protected void ddlChontheoquyche_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowAll();
        }

        protected void rbCount_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowAll();
        }


        public void SExcel()
        {
            try
            {
                DataTable dtE = new DataTable();
                string orderby = rbCount.SelectedValue.ToString();
                string CheckShowTheoVong = ddlChontheoquyche.SelectedValue.ToString();
                string search = txtSearch.Text.Trim();
                string startDate = "";//txtStartDate.Text.Trim();
                string endDate = "";//txtEndDate.Text.Trim();
                string dkCount = rbCount.SelectedValue.ToString();
                string status = rbStatus.SelectedValue.ToString();
                string round = ddlRound.SelectedValue.ToString();
                dtE = ImagesBO.getAllImagesBO(search, startDate, endDate, dkCount, status, round, CheckShowTheoVong, orderby);

                //string filename = "DownloadMobileNoExcel.xls";
                string filename = Server.MapPath("/Excel/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
                System.IO.StringWriter tw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                DataGrid dgGrid = new DataGrid();
                dgGrid.DataSource = dtE;
                dgGrid.DataBind();

                //Get the HTML for the control.
                dgGrid.RenderControl(hw);
                //Write the HTML back to the browser.
                //Response.ContentType = application/vnd.ms-excel;
                Response.ContentType = "application/vnd.ms-excel";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
                Response.BufferOutput = true;
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.Charset = "UTF-8";
                this.EnableViewState = false;
                Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
                Response.Write(tw.ToString());
                Response.End();
                //them duoi .xls vao
                //DataSet ds = new DataSet();
                //dt = BO.Admin.ImagesBO.GetInfomationImagesBO("108");
                //ds.Tables.Add(dt);
                //string filename = Server.MapPath("/Excel/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
                //ExcelLibrary.DataSetHelper.CreateWorkbook(filename, ds);
            }
            catch (Exception)
            {

                throw;
            }
        }

        protected void CmdExcel_Click(object sender, EventArgs e)
        {
            SExcel();
        }
        protected void SendMail(string pGmailEmail, string pGmailPassword, string pTo, string pSubject, string pBody, System.Web.Mail.MailFormat pFormat, string pAttachmentPath)
        {
            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
            myMail.BodyEncoding = System.Text.Encoding.UTF8;
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail);
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword);
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
            myMail.From = pGmailEmail + "@gmail.com";
            myMail.To = pTo;
            myMail.Subject = pSubject;
            myMail.BodyFormat = pFormat;
            myMail.Body = pBody;
            if (pAttachmentPath.Trim() != "")
            {
                System.Web.Mail.MailAttachment MyAttachment = new System.Web.Mail.MailAttachment(pAttachmentPath);
                myMail.Attachments.Add(MyAttachment);
            }
            myMail.Priority = System.Web.Mail.MailPriority.High;
            System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
            System.Web.Mail.SmtpMail.Send(myMail);
        }
    }
}